package com.chen.authority.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.hutool.core.util.StrUtil;
import com.chen.authority.common.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author chengy
 * @date 2022/08/26
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * jsr303 校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response validException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String fullErrorMsg = e.getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(StrUtil.LF));
        return Response.fail(fullErrorMsg);
    }

    /**
     * 上传文件异常
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Response sysException(MaxUploadSizeExceededException e) {
        log.error(e.getMessage(), e);
        return Response.fail("上传文件过大，只能在15MB以内");
    }

    /**
     * 未登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    public Response notLoginException(NotLoginException e) {
        log.error(e.getMessage(), e);
        return Response.unauthorized();
    }

    /**
     * 无此权限异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public Response noPermissionException(NotPermissionException e) {
        log.error(e.getMessage(), e);
        return Response.forbidden();
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Response sysException(RuntimeException e) {
        String errorMessage = e.getMessage();
        log.error(errorMessage, e);
        return Response.fail(errorMessage);
    }

    /**
     * 未知异常
     */
    @ExceptionHandler(Exception.class)
    public Response unknownException(Exception e) {
        log.error(e.getMessage(), e);
        return Response.fail("未知错误");
    }

}
